// pages/addDish/addDish.js
const app = getApp()

Page({
  data: {
    id: '',
    isEdit: false,
    form: {
      name: '',
      category: '家常菜',
      desc: '',
      cookTime: '',
      difficulty: 1,
      image: ''
    },
    categories: [
      '家常菜',
      '汤羹',
      '主食',
      '西餐',
      '小炒',
      '凉菜',
      '甜品'
    ],
    difficultyStars: [1, 2, 3, 4, 5]
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ 
        id: options.id,
        isEdit: true 
      })
      this.loadDishDetail(options.id)
    }
  },

  // 加载菜品详情
  loadDishDetail(id) {
    const db = wx.cloud.database()
    db.collection('dishes')
      .doc(id)
      .get()
      .then(res => {
        this.setData({
          form: res.data
        })
      })
      .catch(err => {
        console.error('加载菜品详情失败：', err)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      })
  },

  // 表单输入
  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`form.${field}`]: e.detail.value
    })
  },

  // 选择分类
  onCategoryChange(e) {
    this.setData({
      'form.category': e.detail.value
    })
  },

  // 选择难度
  onDifficultySelect(e) {
    const difficulty = parseInt(e.currentTarget.dataset.difficulty)
    this.setData({
      'form.difficulty': difficulty
    })
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 上传到云存储
        const cloudPath = `dishes/${Date.now()}-${Math.floor(Math.random() * 1000)}.jpg`
        wx.cloud.uploadFile({
          cloudPath,
          filePath: tempFilePath,
          success: res => {
            this.setData({
              'form.image': res.fileID
            })
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
          },
          fail: err => {
            console.error('上传失败：', err)
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  // 提交表单
  onSubmit() {
    const { form, isEdit } = this.data
    
    // 验证
    if (!form.name) {
      wx.showToast({
        title: '请输入菜品名称',
        icon: 'none'
      })
      return
    }
    
    const db = wx.cloud.database()
    const data = {
      ...form,
      updateTime: db.serverDate()
    }
    
    if (isEdit) {
      // 更新
      db.collection('dishes')
        .doc(this.data.id)
        .update({
          data
        })
        .then(() => {
          wx.showToast({
            title: '更新成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        })
        .catch(err => {
          console.error('更新失败：', err)
          wx.showToast({
            title: '更新失败',
            icon: 'none'
          })
        })
    } else {
      // 新增
      data.createTime = db.serverDate()
      db.collection('dishes')
        .add({
          data
        })
        .then(() => {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        })
        .catch(err => {
          console.error('添加失败：', err)
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          })
        })
    }
  }
})